package com.liuwa.knowledge.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.liuwa.common.utils.StringUtils;
import com.liuwa.common.utils.sign.Md5Utils;
import com.liuwa.kebendiandu.model.Word;
import com.liuwa.knowledge.domain.Book;
import com.liuwa.knowledge.domain.FltrpWord;
import com.liuwa.knowledge.domain.Module;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.FileCopyUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Author: Liuwa
 * @Description:
 * @Date: 2025/4/3
 */
@Service("importService")
public class ImportService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private BookService bookService;

    @Autowired
    private ModuleService moduleService;

    @Autowired
    private FltrpWordService fltrpWordService;

    @Autowired
    private PublisherService publisherService;

    @Transactional(rollbackFor = Exception.class)
    public void executeFltrp(JSONArray bookArray) throws IOException{
        String[] grades = {"一年级", "二年级", "三年级", "四年级", "五年级", "六年级", "初一", "初二", "初三", "高一", "高二", "高三"};
        String publisher = "fltrp";

        for(int i = 0 ; i < bookArray.size(); i++){
            JSONObject bookJson = bookArray.getJSONObject(i);
            String volume = "上册".equals(bookJson.getString("volume")) ? "I": "II";
            String name = bookJson.getString("grade") + bookJson.getString("volume");
            int grade = Arrays.asList(grades).indexOf(bookJson.getString("grade")) + 1;
            int type = 1;
            String bookPath = "/material/book/"+ publisher +"/v" + type + "-" + grade + "-" + volume;

            Book book = new Book();
            book.setPublisher(publisher);
            book.setName(name);
            book.setType(type);
            book.setSubject("English");
            book.setCover(bookPath + "/images/cover.jpg");
            book.setGrade(grade);
            book.setVolume(volume);
            //bookService.insert(book);

            JSONArray moduleArray = bookJson.getJSONArray("modules");
            for(int j = 0; j <moduleArray.size(); j++){
                JSONObject moduleJson = moduleArray.getJSONObject(j);
                String unit1 = moduleJson.getJSONArray("unit").getString(0);
                String title = unit1.replace("Unit 1 ", "");
                Module module = new Module();
                module.setBookId(book.getId());
                module.setName(moduleJson.getString("title"));
                module.setTitle(title);
                //moduleService.insert(module);

                List<Word> words = JSONArray.parseArray(moduleJson.getString("words"), Word.class);

                int displayIndex = 1;
                for(Word word : words){
                    FltrpWord fltrpWord = new FltrpWord();
                    fltrpWord.setWord(word.getWord());
                    fltrpWord.setCn(word.getTranslation());
                    fltrpWord.setIpa(word.getSymbol1());
                    fltrpWord.setAudio(generateFilePath(bookPath + "/audio", word.getWord(), word.getAudio()));
                    fltrpWord.setImage(generateFilePath(bookPath + "/images", word.getWord(),  word.getImage()));
                    fltrpWord.setSentence(word.getSampleSentence());
                    fltrpWord.setSentenceTrans(word.getSampleSentenceTrans());
                    fltrpWord.setSentenceAudio(generateFilePath(bookPath + "/sentence", word.getSampleSentence(), word.getSampleSentenceAudio()));

                    fltrpWord.setBookId(book.getId());
                    fltrpWord.setGrade(grade);
                    fltrpWord.setModule(module.getId());
                    fltrpWord.setUnit(0);
                    fltrpWord.setDifficulty(0);
                    fltrpWord.setViewVolume(0);
                    fltrpWord.setCorrect(0);
                    fltrpWord.setDisplayIndex(displayIndex ++);
                    //fltrpWordService.insert(fltrpWord);
                    //fltrpWords.add(fltrpWord);

                }
            }

            logger.info("{}", JSON.toJSONString(book));

        }
    }

    private String generateFilePath(String parentDir, String text, String fileName) throws IOException {
        if(StringUtils.isEmpty(fileName)){
            return "";
        }
        String extension = FilenameUtils.getExtension(fileName);
        String newPath =  parentDir + "/" + Md5Utils.shortMd5(text + "{"+ extension +"}") + "." + extension;

        String oPath = "E:\\kebendiandu\\material\\cdn.beijinxuetang.com\\uploads\\vocabulary\\" + fileName;
        File oFile = new File(oPath);

        if(oFile.exists()){
            File distFile = new File("D:\\knowledge\\oss\\" + newPath);
            FileUtils.copyFile(oFile, distFile);
        }
        else{
            logger.info("{} => {}", fileName, newPath);
        }


        return newPath;
    }
}
